package com.helei.security.component;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.helei.common.api.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//失败处理控制器
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        if (exception instanceof AccountExpiredException) {
            //账号过期
            out.write(new ObjectMapper().writeValueAsString(Result.er("账号过期")));
        } else if (exception instanceof BadCredentialsException) {
            //密码错误
            out.write(new ObjectMapper().writeValueAsString(Result.er("密码错误")));
        } else if (exception instanceof CredentialsExpiredException) {
            //密码过期
            out.write(new ObjectMapper().writeValueAsString(Result.er("密码过期")));
        } else if (exception instanceof DisabledException) {
            //账户不可用
            out.write(new ObjectMapper().writeValueAsString(Result.er("账户不可用")));
        } else if (exception instanceof LockedException) {
            //账户锁定
            out.write(new ObjectMapper().writeValueAsString(Result.er("账户锁定")));
        } else if (exception instanceof InternalAuthenticationServiceException) {
            //用户不存在
            out.write(new ObjectMapper().writeValueAsString(Result.er("用户不存在")));
        } else {
            out.write(new ObjectMapper().writeValueAsString(Result.er("其他错误")));
        }
        out.flush();
        out.close();
    }
}
